using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ACM.cmsarea08;
using ACM.cmsarea08.Core;
using ACM.cmsarea08.Controls;
using ACM.cmsarea08.Administration;

using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;
using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.Tar;

using MySql.Data.MySqlClient;

namespace ACM.cmsarea08.Administration.Core {
	public partial class ManutenzioneHandler :  System.Web.UI.Page {
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new cmsarea08.Administration.Core.DBClass();
		private ACM.cmsarea08.Function.TextClass tlc = new ACM.cmsarea08.Function.TextClass();

		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
			
		}

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.PagoLoad);
		}
	
		private void PagoLoad(object o , EventArgs e) {
			object  _mode = Request.Form["w"];
			object  _compression = Request.Form["m"];
			object  _operation = Request.Params["op"];
			string operation = string.Empty;
			if(_operation == null ) { Response.Write("NO OP"); return ;}
			operation = _operation.ToString();
			switch ( operation.Trim().ToLower()  ) {
				case "backup":
					LoadBackup(_mode.ToString(), _compression.ToString());break;
				case "restore":
					bool append = true;
					if(Request.Params["file"] == null) { Response.Write("NO FILE"); return; }
					if(Request.Params["append"] != null) { bool.TryParse(Request.Params["append"], out append);  }
					string filepath = Request.Params["file"].ToString();
					this.RestoreBackup(filepath,append);
					break;
				case "download":
					if(Request.Params["file"] == null) { Response.Write("NO FILE"); return; }				
					string comp = "2";
					if(Request.Params["comp"] != null) { comp = Request.Params["comp"]; }									
					string bfile = Request.Params["file"].ToString();
					this.DownloadBackup(bfile,comp);
					break;	
					
			}
			/*
			
			Response.Write("OPERAZIONE: " + _operation);
			operation = _operation.ToString();
			if(operation.Trim().ToLower() == "backup") {
				if(_mode == null || _compression == null ) {
					Response.Write("NO FORM VALUE");
					return;
				}
				LoadBackup(_mode.ToString(), _compression.ToString());
			} else if(operation.Trim().ToLower() == "restore") {
				
			}
			
			*/
			
			
			if(!Page.IsPostBack) {
				
				
			}
			
			
		}
	
		private void DownloadBackup( string filePath, string compressione ) {
			string path = Server.MapPath(filePath);
			System.IO.FileInfo fi = new System.IO.FileInfo(path);
			if(!fi.Exists ) {
				Response.Write("NO FILE");
				return;
			}
			
			FileStream MyFileStream;
			long FileSize;
			MyFileStream = new FileStream(fi.FullName, System.IO.FileMode.Open);
			FileSize = MyFileStream.Length;
			byte[] Buffer = new byte[(int)FileSize];
			MyFileStream.Read(Buffer, 0, (int)FileSize);
			MyFileStream.Close();
			fi.Delete();
			Response.Clear();
			string ext = "";
			switch (compressione.Trim().ToLower()) {
				case "0": ext="rar";break;
				case "1": ext="zip";break;
				default: ext = "bck";break;
			}
			Response.AddHeader("Content-Disposition", "attachment; filename="+
			                   ACM.cmsarea08.Function.TextClass.textclass.SoloTestoNOACC(
			                   	ACM.cmsarea08.mainconfiguration.MainConf.NomePortale
			                   .Replace(" ","_").Trim().ToLower()) + "_" +
			                   DateTime.Now.ToString("yyyyMMdd")  +"."+ext );
			Response.AddHeader("Content-Length", FileSize.ToString());
			Response.ContentType = "application/octet-stream";
			Response.BinaryWrite(Buffer);
			Response.End();		
		}
		
		private void LoadBackup (string mode, string compressione) {
			mode = mode.Trim();
			if(mode.EndsWith(",") )
				mode = mode.Substring(0,mode.Length-1);
			string[] cose = new string[0];
			if(mode.IndexOf(",")!=-1)
				cose = mode.Split(',');
			else
				cose = new string[1] { mode.Trim() };
			//contenuti
			bool cont = false;
			//moduli
			bool mod  = false;
			//menu
			bool men  = false;
			//blocchi visivi
			bool bv  = false;
			//template
			bool tt  = false;			
			//template file
			bool tf  = false;			
			//utenti
			bool uu  = false;			
			//ruoli
			bool rr  = false;			
			//ruoli - menu
			bool rm  = false;			
			//permessi contenuti
			bool rc  = false;			
			//plugins
			bool pp  = false;			
			//plugins files
			bool pf  = false;			
			//configurazione
			bool cc  = false;			
			//all ogni tabella non standard;
			bool all  = false;			
			
			for(int i = 0; i<cose.Length; i++) {
				switch (cose[i].Trim().ToLower()) {
					case "cont":cont = true;break;
					case "mod":mod = true; break;
					case "men":men = true; break;
					case "bv":bv = true; break;
					case "tt":tt = true; break;
					case "tf":tf = true; break;
					case "uu":uu = true; break;
					case "rr":rr = true; break;
					case "rm":rm = true; break;
					case "rc":rc = true; break;
					case "pp":pp = true; break;
					case "pf":pf = true; break;
					case "cc":cc = true; break;
					case "all":all = true; break;
				}
			}
			string path = System.Guid.NewGuid().ToString().Replace("-","");
			string pPath = "/public/" + path + ".temp";
			path = System.AppDomain.CurrentDomain.BaseDirectory + @"\public\" + path + ".temp";
			if(System.IO.File.Exists(path)) {
				System.IO.File.Delete(path);
			}
			System.IO.StreamWriter tempFile = new System.IO.StreamWriter(path,false);
			MySqlConnection mycn = new MySql.Data.MySqlClient.MySqlConnection(ACM.cmsarea08.mainconfiguration.MainConf.DB_ConnectionString);
			MySql.Data.MySqlClient.MySqlTransaction trs;
			MySql.Data.MySqlClient.MySqlCommand cmd;
			//avvia la connessione my sql.
			if(mycn.State!= ConnectionState.Open)
				mycn.Open();
			trs = mycn.BeginTransaction();
			cmd = mycn.CreateCommand();
			cmd.Connection = mycn;
			cmd.Transaction = trs;
			try {
			//elenco tabelle in backup con le selezioni:
			string tables = "contenuti,contenuti_attrib,contenuti_manager,moduli,menu_elemento,menu_tipolink," +
				"blocco_visivo,hplayout,componenti,utentimodelli,ruoli,utentiruoli,user_menu,userpanel,contenutiruoli,"+
				"comonenti,mainconf,admin_menu,utenti,filemanager,admfilemanager";
			string prext = ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle;		
			//avvia il file xml:
			tempFile.WriteLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
			tempFile.WriteLine("<Backup>");
			tempFile.WriteLine("<Author>" +ACM.cmsarea08.Users.CurrentUser.UserName + "</Author>");
			tempFile.WriteLine("<Date>" +System.Xml.XmlConvert.ToString(System.DateTime.Now) + "</Date>");
			tempFile.WriteLine("<Webname>" +ACM.cmsarea08.mainconfiguration.MainConf.NomePortale + "</Webname>");
			tempFile.WriteLine("<Tableprefix>" +ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + "</Tableprefix>");
			tempFile.WriteLine("<Sets>");
			//backup contenuti:
				if(cont) {
					//contenuti, contenuti_attrib, contenuti_manager
					tempFile.WriteLine(writeSet(prext,"contenuti",cmd,true,false));
					tempFile.WriteLine(writeSet(prext,"contenuti_attrib",cmd,true,false));
					tempFile.WriteLine(writeSet(prext,"contenuti_manager",cmd,true,false));
					tempFile.WriteLine(writeSet(prext,"filemanager",cmd,true,false));
				}
			//backup moduli:
				if(mod) {
					//moduli
					tempFile.WriteLine(writeSet(prext,"moduli",cmd,true,false));
				}			
			//backup menu
				if(men) {
					//menu item, 
					tempFile.WriteLine(writeSet(prext,"menu_elemento",cmd,true,false));
					tempFile.WriteLine(writeSet(prext,"menu_tipolink",cmd,true,false));
				}			
			//backup bv
				if(bv) {
					//blocchi visivi, hplayout
					tempFile.WriteLine(writeSet(prext,"blocco_visivo",cmd,true,false));
					tempFile.WriteLine(writeSet(prext,"hplayout",cmd,true,false));
				}			
			//tt 
				if(tt) {
					//template
					tempFile.WriteLine(writeSet(prext,"template",cmd,true,false));
				}	
			//uu
				if(uu) {
					//utenti, utentimodelli
					tempFile.WriteLine(writeSet(prext,"utenti",cmd,true,false));
					tempFile.WriteLine(writeSet(prext,"utentimodelli",cmd,true,false));
				}	
			//rr
				if(rr) {
					//ruoli
					tempFile.WriteLine(writeSet(prext,"ruoli",cmd,true,false));
					tempFile.WriteLine(writeSet(prext,"utentiruoli",cmd,true,false));
				}	
			//rr
				if(rm) {
					//ruoli menu
					tempFile.WriteLine(writeSet(prext,"user_menu",cmd,true,false));
					tempFile.WriteLine(writeSet(prext,"userpanel",cmd,true,false));
				}	
			//rr
				if(rc) {
					//ruoli contenuti
					tempFile.WriteLine(writeSet(prext,"contenutiruoli",cmd,true,false));
				}	
			//pp
				if(pp) {
					//plugins
					tempFile.WriteLine(writeSet(prext,"componenti",cmd,true,false));
				}	
			//cc
				if(cc) {
					//plugins
					tempFile.WriteLine(writeSet(prext,"mainconf",cmd,true,false));
					tempFile.WriteLine(writeSet(prext,"admin_menu",cmd,true,false));
					tempFile.WriteLine(writeSet(prext,"admfilemanager",cmd,true,false));
				}	
			//all:
				if(all) {
					//recupera elenco tabelle:
					string[] tableoc = tables.Split(',');
					System.Collections.ArrayList listabuone = new System.Collections.ArrayList();
					MySql.Data.MySqlClient.MySqlDataReader rdr = null;
					cmd.CommandText = "show tables ;";
					rdr = cmd.ExecuteReader();
					while (rdr.Read()) {
						string tb = rdr.GetString(0);
						bool found = false;
						for(int j = 0 ; j<tableoc.Length;j++){
							if(tableoc[j].ToLower().Trim()==tb.ToLower().Trim()) {
								found=true;continue;
							}
							if((prext + tableoc[j].Trim()).ToLower().Trim()==tb.ToLower().Trim()) {
								found=true;continue;
							}
							
						}
						if(!found) listabuone.Add(tb.Trim());
					}
					rdr.Close();
					if(listabuone.Count>0) {
						for(int lb = 0;lb<listabuone.Count; lb++)
							tempFile.WriteLine(this.writeSet("",listabuone[lb].ToString(),cmd,true,true));
					}
					listabuone.Clear();
				}
			tempFile.WriteLine("</Sets></Backup>");
			} catch {
				
				try {
					if(trs!=null)
						trs.Rollback();
				} catch (MySqlException ex) {
					if(trs.Connection!=null) {
						//reso+="<br/>Errore Transazione : " + ex.GetType() + "\r\n";
						//"<errorTransaction_MySql><![CDATA[" + ex.GetType() + "]]></errorTransaction_MySql>";
						//reso = "<transaction>" + reso + "<errorTransaction></transaction>";
					}
				}	
				Response.Write("ERRORE");
			} finally {
				if(mycn!=null) {
					if(mycn.State!= ConnectionState.Closed)
						mycn.Close();
					mycn.Dispose();
				}
			}
			tempFile.Close();
			if(compressione.Trim()=="2") {
				Response.Write("OK~" + pPath);
				return;
			}
			if(compressione.Trim()=="0") {
				//compressione RAR
			}
			if(compressione.Trim()=="1") {
				//compressione zip
				Crc32 crc32 = new Crc32();
				ZipOutputStream stream = new ZipOutputStream(File.Create(path.Replace("temp","zip")));
				stream.SetLevel(7);
				ZipEntry entry = new ZipEntry(Path.GetFileName(path));
				entry.DateTime = DateTime.Now;
				
				using (FileStream fs = File.OpenRead(path))
				{
				    byte[] buffer = new byte[fs.Length];
				    fs.Read(buffer, 0, buffer.Length);
				    entry.Size = fs.Length;
				    fs.Close();
				    crc32.Reset();
				    crc32.Update(buffer);
				    entry.Crc = crc32.Value;
				    stream.PutNextEntry(entry);
				    stream.Write(buffer, 0, buffer.Length);
				}
 				stream.Finish();
    			stream.Close();
    			System.IO.File.Delete(path);
    			Response.Write( "OK~" + pPath.Replace("temp","zip") );
				return;    			
			}
			
			
			//sono qui verifica il metodo di compressione e poi prosegui.
		}
		
		private void RestoreBackup(string filename, bool append) {
			//verifica este compressione
			
			string resoTest = "<br/>" + DateTime.Now;
			filename = System.AppDomain.CurrentDomain.BaseDirectory + filename.Replace(@"/",@"\");
			System.Xml.XmlTextReader mread = null;
			try {
				//lettura File:
				mread = new System.Xml.XmlTextReader(filename);
				mread.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
				string autore 	= "";
				DateTime data   = DateTime.Now;
				string website 	= "";
				string prefisso = "";
//				System.Collections.ArrayList backup = new System.Collections.ArrayList();
				System.Collections.Generic.List<BackupItem> backup = new System.Collections.Generic.List<BackupItem>();
				bool read_items = false;
				bool closeItem  = false;
				
				
				string lastItem = "";
				string usePrefix = "";
				
				BackupItem tempValue =null;
				resoTest+="</br>";
				
				while (mread.Read()) {
					if(mread.NodeType == System.Xml.XmlNodeType.Text) {
						//resoTest +="TEXTNODE: " + mread.Name + "<br/>";
						switch (lastItem) {
							case "author":
								autore = mread.Value; break;
							case "date":
								DateTime.TryParse(mread.Value, out data);break;
							case "webname":
								website = mread.Value; break;
							case "tableprefix":
								prefisso =mread.Value; break;
								
							case "name":
								if(read_items && tempValue!=null) {
									tempValue.Table = mread.Value;
								}
								break;
							case "item":
								if(read_items && tempValue!=null) {
									tempValue.Data.Add(this.decompressData(mread.Value));
								}
								break;
							case "create":
								if(read_items && tempValue!=null) {
									tempValue.Create = this.decompressData(mread.Value);
								}
								break;
								
								
						}
					}
					if(mread.NodeType == System.Xml.XmlNodeType.CDATA) {
						if(read_items && tempValue!=null && lastItem =="item" ) {
							tempValue.Data.Add(this.decompressData(mread.Value) );
						}
						if(read_items && tempValue!=null && lastItem =="create" ) {
							tempValue.Create = this.decompressData(mread.Value);
						}
						
					}
					if(mread.NodeType == System.Xml.XmlNodeType.EndElement && read_items==true && mread.Name.ToLower().Trim()=="set") {
						backup.Add(tempValue);
						tempValue =null;
					}
					
					if(mread.NodeType == System.Xml.XmlNodeType.Element) {
						//resoTest +="ELEMENTNODE: " + mread.Name + "<br/>";
						lastItem= mread.Name.Trim().ToLower();
						if(mread.Name.Trim().ToLower() == "set") {
							tempValue = new BackupItem();
							tempValue.Prefix = mread.GetAttribute("prefix");
							read_items=true;
						}
					}
				}
				
				//avvia processo di backup da qui:
				MySqlConnection mycn = new MySql.Data.MySqlClient.MySqlConnection(ACM.cmsarea08.mainconfiguration.MainConf.DB_ConnectionString);
				MySql.Data.MySqlClient.MySqlTransaction trs;
				MySql.Data.MySqlClient.MySqlCommand cmd;
				//avvia la connessione my sql.
				if(mycn.State!= ConnectionState.Open)
					mycn.Open();
				trs = mycn.BeginTransaction();
				cmd = mycn.CreateCommand();
				cmd.Connection = mycn;
				cmd.Transaction = trs;
				string resoEX = "";
				System.Collections.Generic.List<LogBackup> esecuzione = new System.Collections.Generic.List<LogBackup>();
				try {
					for(int i = 0;i<backup.Count; i ++) {
						esecuzione.Add( new LogBackup(backup[i].Table ) ) ;
						if ( backup[i].Data.Count==0 ) continue;
						string pref = string.Empty;
						if(backup[i].Prefix.ToLower().Trim()!="none")
							pref = prefisso;
						if(!append) {
							int reso = 0;
							cmd.CommandText = " delete from " +pref + backup[i].Table +" ;" ;
							reso = cmd.ExecuteNonQuery();
							esecuzione[esecuzione.Count-1].Deleted = reso;
						}
						string insbase = "insert into "+pref + backup[i].Table+" VALUES ";
						string insert = insbase;
						for(int d = 0; d<backup[i].Data.Count; d++) {
							insert+= "(" +backup[i].Data[d]+ ")";
							if((d+1) % 10 == 0  && d>0 ) {
								insert+="; " + insbase;
							} else if(d==backup[i].Data.Count-1) insert+=";";  else insert+=", ";
						}
						int resoinsert = 0;
						cmd.CommandText = insert;
						resoinsert= cmd.ExecuteNonQuery();
						esecuzione[esecuzione.Count-1].Inserted = resoinsert;
						esecuzione[esecuzione.Count-1].QueryCount = backup[i].Data.Count;
						//resoEX+="QUERY INSERT: " + insert + "<br/><br/>";
						//resoEX+="RISULTATO INSERIMENTI: " + resoinsert+ "<hr/>";
					}
				} catch (Exception exD) {
					try {
						if(trs!=null)
							trs.Rollback();
//						resoEX+="ECCEZIONE: " + exD.ToString() + "<br/>";
					} catch (MySqlException ex) {
						if(trs.Connection!=null) {
							resoEX+="<br/>Errore Transazione : " + ex.GetType() + "\r\n";
						}
					}				
					esecuzione[esecuzione.Count-1].Error = exD.ToString();
				} finally {
					if(mycn!=null) {
						if(mycn.State!= ConnectionState.Closed)
							mycn.Close();
						mycn.Dispose();
					}
				}
				Response.Write("TEST DATI<br/>Autore: " + autore + "<br/>data: " + data + "<br/>website: " + website + "<br/>prefisso: " + prefisso + "<br/>");
				Response.Write("RISULTATO: <br/>");
				
				for(int i = 0 ;i<esecuzione.Count;i ++) {
					Response.Write("E: " + 	esecuzione[i].Table	 + ", " + 
					               			esecuzione[i].QueryCount + ", " + 
					               			esecuzione[i].Inserted + " # " + 
   											esecuzione[i].Deleted + ", [Errori: "+ 
					               			esecuzione[i].Error+ "]<br/> ");					
				}
			} catch (Exception ex) {
				Response.Write("errore elaborazione file: " + ex.ToString());
			} finally {
				if(mread!=null) mread.Close();
			}
			Response.Write("fine elaborazione");
		}
		
		private string getColumnData(string tipo, object valore) {
			string reso = "";
			switch (tipo.Trim().ToLower()) {
				//interi piccoli	
				case "tinyint": case "smallint":case "int":case "bigint":
					System.Int64 test64 = 0;
					System.Int64.TryParse(valore.ToString(),out test64);
					if(test64<0)
						reso = "'" + test64 + "'";
					else
						reso = test64.ToString();
					break;
					
				case "float": case "double": case "decimal": 
					float testflo = 0;
					float.TryParse(valore.ToString(),out testflo);
					reso = "'" + testflo.ToString().Replace(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator,".") + "'";
					break;
					

				case "datetime": case "date": case "timestamp": case "time":
					DateTime dt = System.DateTime.Now;
					DateTime.TryParse(valore.ToString(),out dt);
					reso = "'" + dt.ToString("yyyy-MM-dd HH:mm:ss") + "'"; break;
				case "varchar": case "blob" : case "text": 
					if (valore is byte[]) 
						reso += "'" + System.Text.Encoding.UTF8.GetString( (byte[]) valore).Replace("'",@"\'") + "'";
					else
						reso = "'" + valore.ToString().Replace("'",@"\'") + "'"; break;
					
				default:
					reso = "'" + valore.ToString().Replace("'",@"\'") + "'";break;
			}
			return reso; //tipo + " -->" + reso;
		}
	
		private string writeSet (string prefisso,  string nomeTabella, MySqlCommand cmd, bool compressRows,bool includeCreate) {
			string reso = "";
			MySql.Data.MySqlClient.MySqlDataReader rdr = null;
			reso = ("<set "+(includeCreate?"prefix=\"none\"":"prefix=\"apply\"")+"><name>"+nomeTabella+"</name>");
			if(includeCreate) {
				cmd.CommandText = "show create table " + prefisso+nomeTabella + "; ";
				rdr = cmd.ExecuteReader();
				while(rdr.Read()) {
					string table = rdr.GetString(1);
					if(table.IndexOf("ENGINE")!=-1) {
						table = table.Substring(0,table.IndexOf("ENGINE"));
					}
					reso+="<create>" +this.compressData(table) + "</create>";
				}
				rdr.Close();
			}
			reso+="<items>";
			cmd.CommandText = "select * from "+prefisso+nomeTabella+" ;";
			rdr = cmd.ExecuteReader();
			
			while (rdr.Read()) {
				
				
				//esegui la lettura.
				string row = "";
				for(int i = 0 ; i<rdr.FieldCount; i++)
					row+= this.getColumnData(rdr.GetDataTypeName(i),rdr.GetValue(i)) + ",";
				if(row.EndsWith(","))
				   row = row.Substring(0,row.Length-1);
				if(compressRows) row = this.compressData(row);
				reso+=("<item><![CDATA["+row+ "]]></item>");
				
			}
			rdr.Close();
			reso+=("</items></set>\n");			
			return reso;
		}
	
		private string compressData(string data) {
			byte[] datab = System.Text.Encoding.UTF8.GetBytes(data);
			//ottenuti i dati
			System.IO.MemoryStream mr = new MemoryStream();
		    ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream stream = 
		    	new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(mr,
		        new ICSharpCode.SharpZipLib.Zip.Compression.Deflater(ICSharpCode.SharpZipLib.Zip.Compression.Deflater.BEST_COMPRESSION), 131072);
		    stream.Write(datab, 0, datab.Length);
		    stream.Close();
		    byte[] outstream = mr.ToArray();
		    return System.Convert.ToBase64String(outstream);
		}
		private string decompressData(string data) {
			byte[] datab = System.Convert.FromBase64String(data);
			//ottenuto il byte array
		    ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream stream = 
		    new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(new MemoryStream(datab));
		    MemoryStream memory = new MemoryStream();
		    byte[] writeData = new byte[4096];
		    int size =-1;
		    size = stream.Read(writeData, 0, writeData.Length);
		    while(size > 0) {
		      memory.Write(writeData, 0, size);
		      size = stream.Read(writeData, 0, writeData.Length);
		    }
		    stream.Close();
		    string constructedString = System.Text.Encoding.UTF8.GetString(memory.ToArray());
		    return constructedString;		
		}
	}
	
	public class BackupItem {
		string _table;
		string _prefix ;
		string _create ;
		ArrayList _data; 
		//prevedere blocco files etc etc.
		private void initMe(string table, string prefix) {
			_table = table;
			_prefix=prefix; 
			_create = string.Empty;
			_data = new ArrayList();
		}
		
		public BackupItem(string table, string prefix) {
			initMe(table,prefix);
		}
		public BackupItem() { 
			initMe("","");
		}
		
		public string Table {
			get { return _table; }
			set { _table = value; }
		}
		public string Prefix { get { return _prefix; } set { _prefix=value;} }
		public ArrayList Data { get { return _data; } }
		public string Create {get {return _create; } set { _create=value; } }
	}
	
	public class LogBackup {
		private string 	_table ;
		private string  _error ; 
		private int 	_deleted ;
		private int 	_inserted; 
		private int 	_previsti;
		
		private bool append;
		
		public LogBackup ( string table ) {
			_table = table;
			_error = string.Empty;
			_deleted = 0; _inserted = 0; _previsti = 0;
		}
		
		public string Table { get { return _table; } }
		public int Deleted { get { return _deleted; } set { _deleted = value; } }
		public int Inserted { get { return _inserted; } set { _inserted = value; } }
		public int QueryCount { get { return _previsti; } set { _previsti = value; } }
		public string Error { get { return _error; } set { _error = value; } }
	}
}


/* 
Tabella di esempio per mappare i dati:
SELECT * FROM demobck ;

insert into demobck values
(1,10,100,1000,500,'23.45','34.34','123.345','123.234',now(),now(),now(),now(),'A','testo vario', 'b','testo bit',
'blobbolo','testolooo','1','uno');

DROP TABLE IF EXISTS `medins_cms`.`demobck`;
CREATE TABLE  `medins_cms`.`demobck` (
  `tiny_int` tinyint(3) unsigned NOT NULL,
  `small_int` smallint(5) unsigned NOT NULL,
  `intero` int(10) unsigned NOT NULL,
  `big_int` bigint(20) unsigned NOT NULL,
  `med_int` mediumint(8) unsigned NOT NULL,
  `fluot` float NOT NULL,
  `doppio` double NOT NULL,
  `decimale` decimal(10,2) NOT NULL,
  `numerico` decimal(10,2) NOT NULL,
  `datacompleta` datetime NOT NULL,
  `databasta` date NOT NULL,
  `tempo` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `orologio` time NOT NULL,
  `carattere` char(1) NOT NULL,
  `variocar` varchar(45) NOT NULL,
  `carbit` char(1) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL,
  `stringabit` varchar(45) CHARACTER SET latin1 COLLATE latin1_bin NOT NULL,
  `blobbo` blob NOT NULL,
  `taesto` text NOT NULL,
  `enuma` enum('0','1') NOT NULL,
  `setto` set('uno','due') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
*/
